#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/10/25 16:40
# @Author  : 胡浩浩
# @File    : common_tools.py
# @IDE     : PyCharm
# @description :
import csv
import json
import socket

import jmespath
import ruamel.yaml
import re


def write_to_csv(file_path, data):
    with open(file_path, 'w', newline='', encoding="utf-8-sig") as file:
        writer = csv.writer(file)
        writer.writerows(data)


def is_jmespath_valid(expression):
    try:
        jmespath.compile(expression)
        return True
    except jmespath.exceptions.ParseError:
        return False


def write_to_yml(file_path, data):
    # 顺序写入新的yml文件中,保证格式不混乱
    with open(file_path, "w", encoding="utf-8") as f:
        ruamel.yaml.round_trip_dump(data, f, default_flow_style=False, allow_unicode=True)


def read_yml(file_path, node=None):
    with open(file_path, "r", encoding="utf-8") as f:
        yaml = ruamel.yaml.YAML(typ='unsafe', pure=True)
        yaml.allow_duplicate_keys = True
        data = yaml.load(f)
    if node:
        return data[node]
    else:
        return data


def write_to_json_file(file_path, data):
    with open(file_path, 'w', encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False)


def read_json_file(file_path):
    try:
        with open(file_path, 'r', encoding="utf-8") as f:
            data = json.load(f)
    except:
        data = {}
    return data

def write_to_log_file(path,data,mode="a"):
    with open(path,mode=mode,encoding="utf-8")as f:
        f.write(data+"\n")

def extract_ip_from_url(url):
    ip_pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
    match = re.search(ip_pattern, url)
    if match:
        return match.group()
    else:
        return None

def get_ip_address():
    hostname = socket.gethostname()
    ip_address = socket.gethostbyname(hostname)
    return ip_address


if __name__ == '__main__':
    ip = get_ip_address()
    print(ip)
